<template>
  <div class="cinema-detail-page">
    <!-- 🎬 影院信息区域 -->
    <section class="cinema-info">
      <div class="cinema-image">
        <img
          v-if="cinemaInfo && cinemaInfo.cinemaImage"
          :src="cinemaInfo.cinemaImage"
          :alt="cinemaInfo.cinemaName"
        />
      </div>

      <div class="cinema-details">
        <h2>{{ cinemaInfo.cinemaName }}</h2>
        <p class="address">{{ cinemaInfo.cinemaAddress }}</p>
        <p class="phone">{{ cinemaInfo.phone }}</p>

        <div class="services" v-if="cinemaInfo.services">
          <h3>影院服务：</h3>
          <ul>
            <li
              v-for="(service, index) in splitServices(cinemaInfo.services)"
              :key="index"
            >
              {{ service }}
            </li>
          </ul>
        </div>
      </div>
    </section>

    <!-- 🎞 正在上映电影 -->
    <section class="movies-section">
      <h2>正在播放</h2>

      <!-- 横向滚动电影列表 -->
      <div class="movies-scroll">
        <div
          v-for="(movie, index) in movies"
          :key="movie.movieId || index"
          class="movie-card"
          :class="{ active: selectedMovieIndex === index }"
          @click="selectMovie(index)"
        >
          <div class="poster">
            <img
              :src="movie.movieImage || '/images/default-movie.png'"
              :alt="movie.movieName"
              @error="(e) => (e.target.src = '/images/default-movie.png')"
            />
          </div>

          <div class="movie-info">
            <h3>{{ movie.movieName }}</h3>
            <p class="score">
              评分：<span>{{ movie.score || "暂无" }}</span>
            </p>
            <p class="type">类型：{{ movie.movieType || "未知" }}</p>
            <p class="duration">时长：{{ movie.durationMinutes }} 分钟</p>
            <p class="actors">主演：{{ movie.actors || "暂无" }}</p>
          </div>
        </div>
      </div>

      <!-- 🎟 场次信息 -->
      <div v-if="selectedMovie" class="session-panel">
        <h3>{{ selectedMovie.movieName }}</h3>
        <p>
          时长：{{ selectedMovie.durationMinutes }} 分钟 | 类型：{{
            selectedMovie.movieType
          }}
        </p>
        <p>主演：{{ selectedMovie.actors }}</p>

        <div v-if="selectedMovie.scheduleList?.length" class="session-list">
          <table>
            <thead>
              <tr>
                <th>放映时间</th>
                <th>放映厅</th>
                <th>售价（元）</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(session, i) in selectedMovie.scheduleList" :key="i">
                <td>{{ session.startTime }}</td>
                <td>{{ session.hallName }}</td>
                <td class="price">¥{{ session.price }}</td>
                <td>
                  <button
                    class="book-btn"
                    @click="goToSeatSelection(selectedMovie, session)"
                  >
                    选座购票
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <p v-else class="no-session">暂无场次信息</p>
      </div>
    </section>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, nextTick } from "vue";
import { useRoute, useRouter } from "vue-router";
import { getCinemaDetail } from "../api/cinema.js";

const route = useRoute();
const router = useRouter();

const cinemaId = route.params.cinemaId; // 影院 ID
const movieIdFromQuery = route.query.movieId; // 从 MovieDetail 带来的 movieId

const cinemaInfo = ref({});
const movies = ref([]);
const selectedMovieIndex = ref(null);

const selectedMovie = computed(() =>
  selectedMovieIndex.value !== null
    ? movies.value[selectedMovieIndex.value]
    : null
);

onMounted(() => {
  fetchCinemaDetail();
});
function selectMovie(index) {
  selectedMovieIndex.value = index;
}
async function fetchCinemaDetail() {
  try {
    const response = await getCinemaDetail(cinemaId);
    console.log("-----------------response------------------");
    console.log(response);
    if (response.data && response.data.data) {
      cinemaInfo.value = response.data.data;

      // ✅ 补充 movieId（防止后端返回 null）
      const movieList = cinemaInfo.value.movieList.map((movie, index) => ({
        ...movie,
        movieId: movie.movieId || index + 1,
      }));

      movies.value = movieList;

      console.log("✅ 修复后电影列表:", movies.value);

      // ✅ 自动选中从 MovieDetail 带来的那部电影
      if (movieIdFromQuery) {
        const index = movies.value.findIndex(
          (m) => String(m.movieId) === String(movieIdFromQuery)
        );

        if (index !== -1) {
          selectedMovieIndex.value = index;

          // ✅ 等 DOM 更新后滚动到选中项
          await nextTick();
          const cards = document.querySelectorAll(".movie-card");
          if (cards[index]) {
            cards[index].scrollIntoView({
              behavior: "smooth",
              block: "nearest",
              inline: "center",
            });
          }
        } else {
          console.warn(
            `⚠️ 未在影院电影列表中找到 movieId: ${movieIdFromQuery}`
          );
        }
      }
    } else {
      console.error("❌ 获取影院详情失败：数据结构异常", response);
    }
  } catch (error) {
    console.error("❌ 获取影院详情失败：", error);
  }
}
function goToSeatSelection(movie, session) {
  console.log("🎬 跳转前 movie 数据：", movie);
  console.log("🕒 选中的场次信息：", session);

  router.push({
    path: "/seatSelection",
    query: {
      cinemaId: cinemaInfo.value.cinemaId,
      cinemaName: cinemaInfo.value.cinemaName,

      movieId: movie.movieId,
      movieName: movie.movieName,
      moviePoster: movie.movieImage, // ✅ 新增：电影海报
      score: movie.score || "暂无",
      duration: movie.durationMinutes ? movie.durationMinutes + "分钟" : "未知",
      type: movie.movieType || "未知",
      actors: movie.actors || "暂无",
      scheduleId: Number(session.scheduleId),
      sessionId: session.sessionId || session.id,
      time: session.startTime,
      hall: session.hallName,
      price: session.price,
    },
  });
}
</script>

<style scoped>
.cinema-detail-page {
  padding: 20px;
  width: 1200px;
  margin: 0 auto;
}

/* 🎬 影院信息 */
.cinema-info {
  display: flex;
  gap: 60px;
  margin-bottom: 40px;
}

.cinema-image img {
  width: 300px;
  height: 200px;
  border-radius: 8px;
  object-fit: cover;
}

/* 🎞 电影区域 */
.movies-section h2 {
  color: #a2131d;
  font-size: 22px;
  margin-bottom: 20px;
}

/* 横向滑动 */
.movies-scroll {
  display: flex;
  overflow-x: auto;
  gap: 30px;
  padding-bottom: 20px;
  scroll-behavior: smooth;
}

.movie-card {
  flex: 0 0 220px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  cursor: pointer;
  transition: all 0.3s ease;
  text-align: center;
  padding-bottom: 10px;
}

.movie-card:hover {
  transform: scale(1.05);
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.15);
}

.movie-card.active {
  border: 3px solid #a2131d;
  transform: scale(1.06);
}

.poster img {
  width: 100%;
  height: 300px;
  object-fit: cover;
  border-radius: 12px 12px 0 0;
}

.movie-info {
  padding: 10px 0;
}

.movie-info h3 {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 6px;
}

.movie-info p {
  font-size: 13px;
  color: #666;
  margin-bottom: 4px;
}

.movie-info .score span {
  color: #e67e22;
  font-weight: bold;
}

/* 🎟 场次信息 */
.session-panel {
  margin-top: 40px;
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.session-panel h3 {
  color: #a2131d;
  font-size: 20px;
  margin-bottom: 10px;
}

.session-list table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 15px;
}

.session-list th,
.session-list td {
  border-bottom: 1px solid #eee;
  padding: 10px 8px;
  text-align: center;
}

.session-list th {
  background-color: #f9f9f9;
  font-weight: 600;
  color: #555;
}

.price {
  color: #a2131d;
  font-weight: bold;
}

.book-btn {
  background: #a2131d;
  color: #fff;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.book-btn:hover {
  background: #c01b25;
}

.no-session {
  color: #888;
  text-align: center;
  padding: 20px 0;
}
</style>
